<template>
  <div class="max-w-5xl mx-auto p-4">
    <!-- 表格标题 -->
    <h2 class="text-2xl font-bold text-gray-800 mb-4 text-center">{{ title }}</h2>

    <!-- 表格容器 -->
    <div class="bg-white rounded-lg shadow-sm hover:shadow-md overflow-hidden transition-all duration-300">
      <table class="min-w-full divide-y divide-gray-200">
        <!-- 表头 -->
        <thead class="bg-gray-50 sticky top-0 z-10">
          <tr>
            <th scope="col"
              class="px-6 py-3 text-left text-base font-semibold text-gray-800 uppercase tracking-wider border-r border-gray-200">
              {{ nameColumnLabel }}
            </th>
            <th scope="col" class="px-6 py-3 text-left text-base font-semibold text-gray-800 uppercase tracking-wider">
              {{ valueColumnLabel }}
            </th>
          </tr>
        </thead>

        <!-- 表体 -->
        <tbody class="bg-white divide-y divide-gray-200">
          <template v-if="hasData">
            <DataRow v-for="(value, key) in jsonData" :key="`${key}-${getUniqueKey(value)}`" :key-name="key"
              :value="value" :index="Object.keys(jsonData).indexOf(key)" />
          </template>
          <template v-else>
            <tr class="h-24">
              <td colspan="2" class="px-6 py-8 text-center">
                <div class="flex flex-col items-center justify-center text-gray-500">
                  <i class="fas fa-file-alt text-2xl mb-2"></i>
                  <span class="text-sm">{{ emptyMessage }}</span>
                </div>
              </td>
            </tr>
          </template>
        </tbody>
      </table>
    </div>
  </div>
</template>

<script setup>
import { computed, unref } from 'vue';
import DataRow from './DataRow.vue';

// 组件属性
const props = defineProps({
  title: {
    type: String,
    default: '数据信息',
    required: false
  },
  nameColumnLabel: {
    type: String,
    default: '名称',
    required: false
  },
  valueColumnLabel: {
    type: String,
    default: '值',
    required: false
  },
  jsonData: {
    type: Object,
    default: () => Object.freeze({}),
    required: true,
    validator: (val) => typeof val === 'object' && val !== null
  },
  emptyMessage: {
    type: String,
    default: '暂无数据',
    required: false
  }
});

// 计算属性：判断是否有数据
const hasData = computed(() => {
  const data = unref(props.jsonData);
  return Object.keys(data).length > 0;
});

// 生成唯一key
const getUniqueKey = (value) => {
  if (value === null || value === undefined) return 'null';
  if (typeof value !== 'object') return String(value);
  return JSON.stringify(value);
};
</script>

<style scoped></style>